package com.gilgamesh.mall.member.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gilgamesh.mall.member.dao.UserDao;
import com.gilgamesh.mall.member.utils.MailUtil;
import com.gilgamesh.mall.member.utils.RandomStringUtil;
import com.gilgamesh.mall.sdk.bean.member.UserEntity;
import com.gilgamesh.mall.sdk.dto.ResponseDTO;
import com.gilgamesh.mall.sdk.dto.member.UserDTO;
import com.gilgamesh.mall.sdk.util.BeanUtil;
import com.gilgamesh.mall.sdk.util.CommonException;
import com.gilgamesh.mall.sdk.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yanm
 * @date 2021/1/8 14:12
 **/
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserService {

    private final UserDao userDao;

    private final RedisTemplate redisTemplate;

    private final MailUtil mailUtil;

    /**
     * 添加
     *
     * @param user 用户对象，id可以自增生成
     * @return 1/0
     * @author yanm
     * @date 2021/1/8 14:18
     **/
    public ResponseDTO<Integer> add(UserEntity user) {
        if(log.isDebugEnabled()){
            log.debug("用户实例,{}",user);
        }
        if(BeanUtil.isLogicalNull(user)){
            throw new CommonException("add时用户不能为空");
        }
        user.setCreateTime(new Date());
        if(StringUtil.isNotEmpty(user.getPassword())) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        }
        ResponseDTO<Integer> responseDTO = new ResponseDTO<>();
        responseDTO.setData(userDao.insert(user));
        if(responseDTO.getData() == 1){
            responseDTO.setCode("0");
            responseDTO.setMessage("success");
            responseDTO.setSuccess(Boolean.TRUE);
        }
        return responseDTO;
    }

    /**
     * 添加
     *
     * @param user 用户对象
     * @return 1/0
     * @author yanm
     * @date 2021/1/8 14:18
     **/
    public ResponseDTO<Integer> updateById(UserEntity user) {
        if(log.isDebugEnabled()){
            log.debug("用户实例,{}",user);
        }
        if(BeanUtil.isLogicalNull(user)){
            throw new CommonException("add时用户不能为空");
        }
        ResponseDTO<Integer> responseDTO = new ResponseDTO<>();
        responseDTO.setData(userDao.updateById(user));
        if(responseDTO.getData() == 1){
            responseDTO.setCode("0");
            responseDTO.setMessage("success");
            responseDTO.setSuccess(Boolean.TRUE);
        }
        return responseDTO;
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     * @return 1/0
     * @author yanm
     * @date 2021/1/8 14:19
     **/
    public ResponseDTO<Integer> deleteById(Long id) {
        ResponseDTO<Integer> responseDTO = new ResponseDTO<>();
        responseDTO.setData(userDao.deleteById(id));
        if(responseDTO.getData() == 1){
            responseDTO.setCode("0");
            responseDTO.setMessage("success");
            responseDTO.setSuccess(Boolean.TRUE);
        }
        return responseDTO;
    }

    public ResponseDTO<List<UserEntity>> select(UserEntity user) {
        if(log.isDebugEnabled()){
            log.debug("用户实例,{}",user);
        }
        if(BeanUtil.isLogicalNull(user)){
            throw new CommonException("add时用户不能为空");
        }
        Wrapper wrapper = new QueryWrapper(user);
        ResponseDTO<List<UserEntity>> responseDTO =new ResponseDTO<>();
        responseDTO.setData(userDao.selectList(wrapper));
        if(responseDTO.getData()!=null){
            responseDTO.setCode("0");
            responseDTO.setMessage("success");
            responseDTO.setSuccess(Boolean.TRUE);
        }
        return responseDTO;
    }

    //TODO:登录验证
    public ResponseDTO<UserDTO> check(UserEntity user) {
        System.err.println(user);
        if (log.isDebugEnabled()) {
            log.debug("用户实例,{}", user);
        }
        if (BeanUtil.isLogicalNull(user)) {
            throw new CommonException("check时用户不能为空");
        }
        if ( !StringUtils.isNotBlank(user.getNumber())  || !StringUtils.isNotBlank(user.getPassword())) {
            throw new CommonException("登陆使用账号(邮箱或手机)或密码不能为空");
        }
        String number = user.getNumber();
        if(number.contains("@")){
            user.setMail(number);
        }else if(number.length() == 11){
            user.setPhoneNumber(number);
        }else{
            throw new CommonException("请输入正确的邮箱号或者密码");
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        Wrapper<UserEntity> wrapper = new QueryWrapper(user);
        ResponseDTO<UserDTO> responseDTO = new ResponseDTO<>();
        UserEntity userEntity = userDao.selectList(wrapper).get(0);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userEntity, userDTO);
        responseDTO.setData(userDTO);
        if (responseDTO.getData() != null) {
            responseDTO.setCode("0");
            responseDTO.setMessage("success");
            responseDTO.setSuccess(Boolean.TRUE);
        }
        return responseDTO;
    }


    public ResponseDTO<UserEntity> selectById(Long id) {
        ResponseDTO<UserEntity> responseDTO = new ResponseDTO<>();
        responseDTO.setData(userDao.selectById(id));
        if(responseDTO.getData()!=null){
            responseDTO.setCode("0");
            responseDTO.setMessage("success");
            responseDTO.setSuccess(Boolean.TRUE);
        }
        return responseDTO;
    }

    //TODO:通过邮箱注册--获取验证码
    public ResponseDTO<String> geMailVerifiCode(UserEntity user) {
        if (log.isDebugEnabled()) {
            log.debug("用户实例,{}", user);
        }
        if (!StringUtils.isNotBlank(user.getMail()) || !StringUtils.isNotBlank(user.getPassword())) {
            throw new CommonException("registerByEmail时用户不能为空");
        }
        String to = user.getMail();
        //生成6位随机数作为验证码
        String verifiCode = RandomStringUtil.getRandom6Bit();
        String subject = "gilgamesh_verification";
        String content = "您的验证码为"+verifiCode+"请在5分钟内输入验证码。切勿泄露给他人";
        mailUtil.sendSimpleMail(to,subject,content);
        redisTemplate.opsForValue().set(to,verifiCode,30000, TimeUnit.SECONDS);
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setData(verifiCode);
        responseDTO.setCode("0");
        responseDTO.setMessage("验证码发送成功");//其实我不知道有没有发送成功
        responseDTO.setSuccess(Boolean.TRUE);
        return responseDTO;
    }

    //TODO:通过邮箱注册---校验验证码并存入数据库
    public ResponseDTO<Integer> verifiyAndRegisterMail(UserEntity user) {
        String mail = user.getMail();
        String verifiCode = user.getVerifiCode();
        String verifiCode2 = (String) redisTemplate.opsForValue().get(mail);
        System.err.println(verifiCode.equals(verifiCode2));

        if(!verifiCode2.equals(verifiCode)){
            throw new CommonException("请输入正确的验证码");
        }else if(verifiCode2.equals(verifiCode)){
            //设置邮箱号
            user.setMail(mail);
            //设置用户昵称
            user.setUserName("yk_" + RandomStringUtil.getRandom8Bit());
            //设置user_id
            user.setUserId(RandomStringUtil.getRandom10Bit());
            //保存确认密码
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
            user.setCreateTime(new Date());
            ResponseDTO<Integer> responseDTO = new ResponseDTO<>();
            responseDTO.setData(userDao.addByMail(user));
            if (responseDTO.getData() == 1) {
                responseDTO.setCode("0");
                responseDTO.setMessage("success");
                responseDTO.setSuccess(Boolean.TRUE);
            }
            return responseDTO;
        }
        return null;

    }

    //TODO:通过手机号注册
    public ResponseDTO<Integer> registerByPhone(UserEntity user){
        if (log.isDebugEnabled()) {
            log.debug("用户实例,{}", user);
        }
        if (StringUtils.isBlank(user.getPhoneNumber()) || StringUtils.isBlank(user.getPassword())) {
            throw new CommonException("registerByPhone时用户不能为空");
        }
        ResponseDTO responseDTO = new ResponseDTO();

        if(queryPhone(user.getPhoneNumber())){
            //设置用户名为手机号，登陆用
            user.setName(user.getPhoneNumber());
            //设置用户昵称
            user.setUserName("yk_" + RandomStringUtil.getRandom8Bit());
            //设置user_id
            user.setUserId(RandomStringUtil.getRandom10Bit());
            //保存确认密码
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
            user.setCreateTime(new Date());
            responseDTO.setData(userDao.addByPhone(user));
            responseDTO.setCode("0");
            responseDTO.setSuccess(Boolean.TRUE);
            responseDTO.setMessage("注册成功");
        }else {
            responseDTO.setData("0");
            responseDTO.setCode("1");
            responseDTO.setSuccess(Boolean.FALSE);
            responseDTO.setMessage("此手机号已被注册过");

        }

        return responseDTO;

    }


    //查询邮箱号是否已注册过
    public ResponseDTO<Integer> queryMail(String mail) {
        if (StringUtils.isBlank(mail)) {
            throw new CommonException("mail不能为空");
        }

        System.err.println(userDao.isExistPhone("18862705236")+"666");
        ResponseDTO responseDTO = new ResponseDTO();
        if( userDao.isExistMail(mail) == null) {
            System.err.println(userDao.isExistMail(mail)+"11111");
            responseDTO.setData(0);
            responseDTO.setCode("0");
            responseDTO.setMessage("此邮箱号未被注册过");
            responseDTO.setSuccess(Boolean.TRUE);
        }else {
            System.err.println(userDao.isExistMail(mail)+"22222");
            responseDTO.setData(1);
            responseDTO.setCode("1");
            responseDTO.setMessage("此邮箱号已被注册过");
            responseDTO.setSuccess(Boolean.FALSE);
        }
        return responseDTO;


    }

    //查询手机号是否已注册过
    public Boolean queryPhone(String phoneNumber) {
        if (StringUtils.isBlank(phoneNumber)) {
            throw new CommonException("phoneNumber不能为空");
        }
        if( userDao.isExistPhone(phoneNumber) == null) {
            return true;
        }else {
            return false;
        }

    }




}
